package com.tanhua.dubbo.service.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.common.vo.MessageResult;
import com.tanhua.dubbo.api.MessageApi;
import com.tanhua.dubbo.pojo.Message;
import com.tanhua.dubbo.enums.MessageState;
import com.tanhua.dubbo.pojo.Publish;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(version = "1.0.0", interfaceClass = MessageApi.class)
public class MessageApiImpl implements MessageApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private QuanZiApiImpl quanZiApi;

    @Override
    public String reject(String[] ids, MessageState ms) {
        try {
            updateStatu(ids, ms);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

        return "true";
    }

    @Override
    public String pass(String[] ids, MessageState ms) {
        try {
            updateStatu(ids, ms);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

        return "true";
    }

    @Override
    public String undo(String[] ids, MessageState ms) {

        try {
            updateStatu(ids, ms);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

        return "true";
    }

    @Override
    public String top(String publishId) {
        try {
            setTop(publishId);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
        return "true";
    }

    @Override
    public String cancelTop(String publishId) {
        try {
            cancelSetTop(publishId);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
        return "true";
    }

    @Override
    public Message getMessage(String publishId) {
        Message message = mongoTemplate.findOne(Query.query(Criteria.where("publishId").is(new ObjectId(publishId))), Message.class);
        return message;
    }

    @Override
    public Integer getAllCount() {
        Query query = new Query();
        long count = mongoTemplate.count(query, Message.class);
        return Convert.toInt(count);
    }

    @Override
    public Integer getStateCount(String desc) {
        if ("all".equals(desc)){
            Query query = new Query();
            long count = mongoTemplate.count(query, Message.class);
            return Convert.toInt(count);
        }
        if ("3".equals(desc)){
            Query query = new Query();
            query.addCriteria(Criteria.where("messageState").is("3"));

            long count = mongoTemplate.count(query, Message.class);
            return Convert.toInt(count);
        }
        if ("4".equals(desc)){
            Query query = new Query();
            query.addCriteria(Criteria.where("messageState").is("4"));
            long count = mongoTemplate.count(query, Message.class);
            return Convert.toInt(count);
        }
        if ("5".equals(desc)){
            Query query = new Query();
            query.addCriteria(Criteria.where("messageState").is("5"));
            long count = mongoTemplate.count(query, Message.class);
            return Convert.toInt(count);
        }
        return null;
    }

    @Override
    public MessageResult findByUserid(Map<String, String> params,Long userId) {

        Integer pagesize = Convert.toInt(params.get("pagesize"));
        Integer page = Convert.toInt(params.get("page"));
        PageRequest pageRequest = PageRequest.of(Convert.toInt(page) - 1, Convert.toInt(pagesize));

        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));

        query.with(Sort.by(Sort.Order.desc("top")));
        //两个排序字段是一体的要么为空要么都有值，说明本次为排序查询
        String sortProp = params.get("sortProp");
        String sortOrder = params.get("sortOrder");
        if (StringUtils.isNotEmpty(sortProp)) {
            if ("ascending".equals(sortOrder)){
                query.with(Sort.by(
                        Sort.Order.asc(sortProp)
                ));
            }
            if ("descending".equals(sortOrder)){
                query.with(Sort.by(
                        Sort.Order.desc(sortProp)
                ));
            }
        }

        query.with(pageRequest);

        List<Message> messageList = mongoTemplate.find(query, Message.class);
        long count = mongoTemplate.count(query, Message.class);

        MessageResult messageResult = new MessageResult();
        messageResult.setCounts(count);
        messageResult.setItems(messageList);
        return messageResult;
    }

    @Override
    public MessageResult findByManyQuery(Map<String, String> params) {
        Integer pagesize = Convert.toInt(params.get("pagesize"));
        Integer page = Convert.toInt(params.get("page"));
        PageRequest pageRequest = PageRequest.of(Convert.toInt(page) - 1, Convert.toInt(pagesize));

        Query query = new Query();

        //用户id如果不为空，实现的是用户详情页下的动态记录
        String uid = params.get("uid");
        if (StringUtils.isNotEmpty(uid)) {
            MessageResult ms = findByUserid(params,Convert.toLong(uid));

            return ms;
        }

        //用户id若不为空 说明为单条数据查询
        String id = params.get("id");
        if (StringUtils.isNotEmpty(id)) {
            query.addCriteria(Criteria.where("userId").is(Convert.toLong(id)));
        }

        //state为all说明为查询全部
        String state = params.get("state");
        if (StringUtils.isNotEmpty(state) && StringUtils.equals(state, "all")) {

        }
        //为3表示查询待审核
        if (StringUtils.isNotEmpty(state) && StringUtils.equals(state, "3")) {
            query.addCriteria(Criteria.where("messageState").is("3"));
        }
        //为4表示查询已通过
        if (StringUtils.isNotEmpty(state) && StringUtils.equals(state, "4")) {

            query.addCriteria(Criteria.where("messageState").is("4"));
        }
        //为5表示查询已驳回
        if (StringUtils.isNotEmpty(state) && StringUtils.equals(state, "5")) {

            query.addCriteria(Criteria.where("messageState").is("5"));
        }


        //默认值为 -1-1  有值说明为时间范围查询
        String ssd = params.get("sd");
        String sed = params.get("ed");
        if (!("-1".equals(ssd) && "-1".equals(sed))) {
            Long sd = Convert.toLong(ssd);
            Long ed = Convert.toLong(sed);

          query.addCriteria(Criteria.where("createDate").gte(sd).andOperator(Criteria.where("createDate").lte(ed)));
        }

        //两个排序字段是一体的要么为空要么都有值，说明本次为排序查询
        String sortProp = params.get("sortProp");
        String sortOrder = params.get("sortOrder");
        if (StringUtils.isNotEmpty(sortProp)) {
            if ("ascending ".equals(sortOrder)){
                query.with(Sort.by(
                        Sort.Order.asc(sortProp)
                ));
            }
            if ("descending".equals(sortOrder)){
                query.with(Sort.by(
                        Sort.Order.desc(sortProp)
                ));
            }
        }

        query.with(pageRequest);

        List<Message> messages = mongoTemplate.find(query, Message.class);
        long count = mongoTemplate.count(query, Message.class);

        MessageResult messageResult = new MessageResult();
        messageResult.setCounts(count);
        messageResult.setItems(messages);
        return messageResult;
    }

    @Override
    public List<Publish> filterPublish(List<Publish> publishList) {
        List<ObjectId> collect = publishList.stream().map(Publish::getId).collect(Collectors.toList());

        //获取过滤后的message
        List<Message> messageList = mongoTemplate.find(Query.query(Criteria.where("publishId").in(collect).and("messageState").is("4")), Message.class);
        List<ObjectId> filtercollect = messageList.stream().map(Message::getPublishId).collect(Collectors.toList());
        List<Publish>  list= new ArrayList<>();
        //遍历已通过的publishId集合
        for (ObjectId objectId : filtercollect) {
            Publish publish = quanZiApi.queryPublishById(ObjectUtil.toString(objectId));
            list.add(publish);
        }

        return list;
    }


    private void updateStatu(String[] ids, MessageState ms) {
        for (String id : ids) {
            Message messg = mongoTemplate.findOne(Query.query(Criteria.where("publishId").is(new ObjectId(id))), Message.class);

                ObjectId zid = messg.getId();
                Query query = new Query();
                query.addCriteria(Criteria.where("publishId").is(new ObjectId(id)).and("_id").is(zid));
                Update update = new Update();
                update.set("messageState", ms.getState());
                mongoTemplate.upsert(query, update, Message.class);

        }
    }

    private void setTop(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("publishId").is(new ObjectId(id)));
        Update update = new Update();
        update.set("top", 2);

        mongoTemplate.updateFirst(query, update, Message.class);
    }

    private void cancelSetTop(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("publishId").is(new ObjectId(id)));
        Update update = new Update();
        update.set("top", 1);

        mongoTemplate.updateFirst(query, update, Message.class);
    }

}
